package com.element.oauth2.utils;

import com.element.oauth2.constant.SecurityParams;
import com.element.oauth2.model.entity.AuthUserE;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;

import java.util.Set;

/**
 * @auther zhangwj
 * @date 2021/4/12 下午7:50
 */
public class SecurityUtil {

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static AuthUserE getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    public static String getAppId() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getAppId(authentication);
    }

    public static Set<String> getScopeUrls() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getScopeUrls(authentication);
    }

    /**
     * 获取用户
     */
    private static AuthUserE getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof DefaultOAuth2User) {
            DefaultOAuth2User defaultOAuth2User = (DefaultOAuth2User) principal;
            return defaultOAuth2User.getAttribute(SecurityParams.USER_INFO);
        }
        return null;
    }

    /**
     * 获取客户端ID
     *
     * @param authentication 授权信息
     * @return 客户端ID
     */
    private static String getAppId(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof DefaultOAuth2User) {
            DefaultOAuth2User defaultOAuth2User = (DefaultOAuth2User) principal;
            return defaultOAuth2User.getAttribute(SecurityParams.CLIENT_ID);
        }
        return null;
    }

    private static Set<String> getScopeUrls(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof DefaultOAuth2User) {
            DefaultOAuth2User defaultOAuth2User = (DefaultOAuth2User) principal;
            return defaultOAuth2User.getAttribute(SecurityParams.SCOPE);
        }
        return null;
    }
}
